package com.ruoyi.system.util;

public class SnowflakeIDGenerator {
    // 起始的时间戳，2023-01-01 00:00:00 GMT
    private static final long START_TIMESTAMP = 1577836800000L;

    // 每一部分占用的位数
    private static final long SEQUENCE_BIT = 12; // 序列号占用的位数
    private static final long MACHINE_BIT = 5;   // 机器标识占用的位数

    // 每一部分的最大值
    private static final long MAX_SEQUENCE = -1L ^ (-1L << SEQUENCE_BIT); // 序列号的最大值
    private static final long MAX_MACHINE_NUM = -1L ^ (-1L << MACHINE_BIT); // 支持的最大机器数量

    // 每一部分向左的位移
    private static final long MACHINE_LEFT = SEQUENCE_BIT;
    private static final long TIMESTAMP_LEFT = SEQUENCE_BIT + MACHINE_BIT;

    private long machineId;     // 机器标识
    private long sequence = 0L; // 序列号
    private long lastTimestamp = -1L; // 上一次时间戳

    public SnowflakeIDGenerator(long machineId) {
        if (machineId > MAX_MACHINE_NUM || machineId < 0) {
            throw new IllegalArgumentException("MachineId can't be greater than " + MAX_MACHINE_NUM + " or less than 0");
        }
        this.machineId = machineId;
    }

    // 生成下一个ID
    public synchronized long nextId() {
        long timestamp = getTimestamp();

        // 如果当前时间小于上一次ID生成的时间戳，说明系统时钟回退过，此时应当抛出异常
        if (timestamp < lastTimestamp) {
            throw new RuntimeException("Clock moved backwards. Refusing to generate id");
        }

        // 如果是同一时间生成的，则进行毫秒内序列
        if (lastTimestamp == timestamp) {
            sequence = (sequence + 1) & MAX_SEQUENCE;
            // 毫秒内序列溢出
            if (sequence == 0) {
                // 阻塞到下一个毫秒，获得新的时间戳
                timestamp = tilNextMillis(lastTimestamp);
            }
        } else {
            sequence = 0L;
        }

        // 上次生成ID的时间戳
        lastTimestamp = timestamp;

        // 移位并通过或运算拼到一起组成64位的ID
        return ((timestamp - START_TIMESTAMP) << TIMESTAMP_LEFT) // 时间戳部分
                | (machineId << MACHINE_LEFT) // 机器标识部分
                | sequence; // 序列号部分
    }

    // 阻塞到下一个毫秒，直到获得新的时间戳
    private long tilNextMillis(long lastTimestamp) {
        long timestamp = getTimestamp();
        while (timestamp <= lastTimestamp) {
            timestamp = getTimestamp();
        }
        return timestamp;
    }

    // 获取当前时间戳
    private long getTimestamp() {
        return System.currentTimeMillis();
    }

    public static void main(String[] args) {
        // 创建一个雪花ID生成器，传入机器ID
        SnowflakeIDGenerator generator = new SnowflakeIDGenerator(1);

        // 生成5个ID并打印输出
        for (int i = 0; i < 5; i++) {
            long id = generator.nextId();
            System.out.println("Generated ID: " + id);
        }
    }
}
